package com.litong.litongjiaoyu.controller;

import com.alibaba.fastjson.JSONObject;
import com.litong.litongjiaoyu.annotation.IgnoreAuth;
import com.litong.litongjiaoyu.entity.SysCourse;
import com.litong.litongjiaoyu.model.WXSessionModel;
import com.litong.litongjiaoyu.service.CommenService;
import com.litong.litongjiaoyu.service.CourseService;
import com.litong.litongjiaoyu.utils.HttpClientUtil;
import com.litong.litongjiaoyu.utils.JSONResult;
import com.litong.litongjiaoyu.utils.JsonUtil;
import com.litong.litongjiaoyu.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CommenController
 * @Description 用于学生端和教师端公共的实现方法
 * @Author jingz
 * @Date 2019/7/18 10:03
 * @Version 1.0
 **/
@RestController
@RequestMapping("/commen")
public class CommenController {

    private Logger log = LoggerFactory.getLogger(CommenController.class);

    private String appid = "wx261c8778d717f430";
    private String appsecret = "9c9d7048df611a1958b3717b637e49b7";
    private String OpenId = "";
    @Autowired
    private CommenService commenService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private PicController picController;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取全部老师手机号
     * @return
     */
    @IgnoreAuth
    @ResponseBody
    @PostMapping("/callTeacher")
    public JSONResult callTeachers(String campus){
        return JSONResult.ok(commenService.callTeacher(campus));
    }



    /**
     * @return com.litong.litongjiaoyu.utils.JSONResult
     * @Author jingz
     * @Description 查询两个表中是否存在该openid
     * @Date 9:54 2019/7/19
     * @Param [code, postion]
     **/
    @ResponseBody
    @RequestMapping(value = "/gethaveopenid", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public JSONResult selectOpenId(String code, String postion) {
        String Url = "https://api.weixin.qq.com/sns/jscode2session?";
        Map<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("secret", appsecret);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        //传回微信服务器并接收session_key，openid
        String result = HttpClientUtil.doGet(Url, param);
        WXSessionModel model = JsonUtil.jsonToPojo(result, WXSessionModel.class);
        OpenId = model.getOpenid();
        String a = postion;
        int student = commenService.selectOpenID(OpenId);
        int teacher = commenService.selectOpenIDByTeacher(OpenId);
        if (student == 1 || teacher == 1) {
            return JSONResult.ok(200, "success", OpenId);

        } else {
            return JSONResult.errorMsg("fail", OpenId);
        }
    }

    /**
     * @return com.litong.litongjiaoyu.utils.JSONResult
     * @Author jingz
     * @Description 获取拥有该openid的人的职位
     * @Date 13:25 2019/7/20
     * @Param [openid]
     **/
    @ResponseBody
    @RequestMapping(value = "/selectposition", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public JSONResult selectPosition(String openid) {
        int student = commenService.selectOpenID(openid);
        int teacher = commenService.selectOpenIDByTeacher(openid);
        if (student == 1 || teacher == 1) {
            if (student == 1) {

                return JSONResult.ok("student");
            } else if (teacher == 1) {
                return JSONResult.ok("teacher");
            } else {
                return JSONResult.errorMsg("NotHave");
            }
        } else {
            return JSONResult.errorMsg("fail", OpenId);
        }
    }

    /**
     * @return com.litong.litongjiaoyu.utils.JSONResult
     * @Author jingz
     * @Description 在数据库中获取所有班级
     * @Date 13:26 2019/7/20
     * @Param []
     **/
    @ResponseBody
    @RequestMapping(value = "/querytclass", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public JSONResult queryTclass(String campus) {
        List<String> tclass = commenService.queryClass(campus);
        return JSONResult.ok(tclass);
    }


    /**
     * 课程区域
     */

    /**
     * 微信小程序通过json获取主页推荐课程
     *
     * @return
     */
    @IgnoreAuth
    @ResponseBody
    @GetMapping("/getrecommend")
    public JSONResult getRecommend() {
        List<Object> coursetable = redisUtil.lGet("Recommend",0, -1);

        List<SysCourse> sysCourses = null;




        return JSONResult.ok(coursetable);
    }

    /**
     * 微信小程序获取所有课程部分信息
     *
     * @return
     */
    @IgnoreAuth
    @ResponseBody
    @GetMapping("/querycourse")
    public JSONResult queryCourse() {
        List<SysCourse> coursetable = courseService.query();

        return JSONResult.ok(coursetable);
    }


    @ResponseBody
    @GetMapping("/getAudition")
    public JSONResult getAudition() {

        return JSONResult.ok(redisUtil.lGet("Audition", 0, -1));
    }

    /**
     * 微信小程序获取课程全部信息
     *
     * @return
     */
    @IgnoreAuth
    @ResponseBody
    @PostMapping("/getCourse")
    public JSONResult getCourseById(long id) {
        SysCourse coursetable = new SysCourse();
        coursetable.setId(id);

        coursetable = courseService.getCourse(id);

        return JSONResult.ok(coursetable);
    }

    /**
     * 获取除试听课程外的所有课程
     * @return
     */
    @ResponseBody
    @GetMapping("/getExcellentCourses")
    public JSONResult getExcellentCourses(){
        return JSONResult.ok(redisUtil.lGet("ExcellentCourses", 0, -1));
    }

    /**
     * 添加课程
     * @param sysCourse
     * @return
     */
    @ResponseBody
    @PostMapping("/insertcourse")
    public JSONResult insertCourse(@RequestBody SysCourse sysCourse) {
        try {
            return JSONResult.ok(courseService.insert(sysCourse));
        } catch (Exception e) {
            log.error(e.getMessage());
            return JSONResult.errorMsg(e.getMessage());
        }
    }


    /**
     * 更新课程信息
     * @param sysCourse
     * @return json
     */
    @ResponseBody
    @PostMapping("/updateCourse")
    public  JSONResult updateCourse(@RequestBody SysCourse sysCourse) {
        log.info("开始更新课程信息");

        log.info("图片检查完成，开始更新数据库");

        if (courseService.update(sysCourse) > 0) {
            log.info("更新课程信息成功！");
            return JSONResult.ok("success");
        } else {
            log.info("更新课程失败！");
            return JSONResult.errorException("fail");
        }
    }

    /**
     * 单个删除
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/delete")
    public JSONResult delete(long id) {
        if (courseService.delete(id) > 0) {
            return JSONResult.ok("success");
        } else {
            return JSONResult.errorMsg("fail");
        }
    }


    /**
     * 批量删除
     * @param ids
     * @return
     */
    @ResponseBody
    @PostMapping("/deleteBatch")
    public JSONResult deleteBatch(long[] ids) {
        if (courseService.batchDelete(ids) > 0) {
            return JSONResult.ok("success");
        } else {
            return JSONResult.errorMsg("fail");
        }
    }

    /**
     * 获取可预约老师名单
     * @return
     */
    @IgnoreAuth
    @ResponseBody
    @GetMapping("/getteacher")
    public JSONResult getTeacher() {
        return JSONResult.ok(commenService.getTeacher());
    }
    
    /**
     * 获取可以聊天的老师列表
     * @param jsonObject 校区名称
     * @return json
     */
    @ResponseBody
    @PostMapping("/getteachergroup")
    public JSONResult getTeacherGroup(@RequestBody JSONObject jsonObject) {
        return JSONResult.ok(this.commenService.getTeacherGroup(jsonObject.getString("campus")));
    }
    
    /**
     * 获取师生聊天中学生列表
     *
     * @param jsonObject 所在校区
     *
     * @return 学生列表
     */
    @PostMapping("/getstudentgroup")
    @ResponseBody
    public JSONResult getStudentGroupWithClassName (@RequestBody JSONObject jsonObject) {
        return JSONResult.ok(this.commenService.getStudentGroupWithClassName(jsonObject.getString("campus")));
    }


    /**
     * @Author jingz
     * @Description 发送预约信息给指定老师
     * @Date 15:16 2019/9/10
     * @Param [reservation]
     * @return com.litong.litongjiaoyu.utils.JSONResult
     **/
//    @PostMapping("/reservation")
//    public JSONResult Reservation(@RequestBody WxReservation reservation) {
//        //微信小程序通知发送类
//        PushController pushController = new PushController();
//        //获取所需要的openId
//        String openId = "此处为获取到的通知人的openid";
//        String formId = "";
//        //判断是否为试听课程，是发送给安排人
//        if (reservation.getTeacherNumber() == null || reservation.getTeacherNumber() == "") {
//
//            openId = "此处修改为固定人选";
//            boolean s = pushController.push(openId, formId, "内容1","内容1","内容1","内容1");
//
//            if (s == true) {
//                //预约信息加入数据库
//
//                //返回发送成功信息
//                return JSONResult.ok("success");
//            } else {
//                return JSONResult.errorMsg("fail");
//            }
//        } else {
//            openId = "此处根据工号获取老师openid";
//
//            boolean s = pushController.push(openId, formId, "内容1","内容1","内容1","内容1");
//
//            if (s == true) {
//                //预约信息加入数据库
//
//                //返回发送成功信息
//                return JSONResult.ok("success");
//            } else {
//                return JSONResult.errorMsg("fail");
//
//            }
//        }
//
//    }
}
